var xhrRegister;
var xhrValidate;
var xhrPasswordStrength;

var vfield;

var NULL_FST_NAME = 100;     // First name required
var NULL_LST_NAME = 101;     // Last name required
var NULL_EMAIL = 110;        // Email required
var EMAIL_NT_UNIQUE = 111;   // Email already registered
var INVALID_EMAIL = 112;     // Invalid email format
var EMAIL_NT_REG = 113;      // Email not registered
var ACC_ACTIVATED = 114;     // Email already activated
var INVALID_CONTACT = 120;   // Invalid contact format
var INVALID_DOB = 131;       // Invalid DOB
var NULL_DOB = 132;          // Null DOB
var INVALID_CC_EXPIRY = 140; // Invalid CC Expiry date
var CC_EXPIRED = 141;        // CC expired
var INVALID_CC_NUM = 142;    // Invalid CC number
var INVALID_CC_ISSUER = 143; // Wrong issuer
var INVALID_PWD = 150;       // Invalid password
var NULL_PWD = 151;          // Password required
var PWD_MISMATCH = 152;      // Password mismatch
var SYS_ERR = 200;           // Generic system error

/*****************************************************************************/
/* xhrRegister */
function registerCustomer() {

    /* create xhrRegister */
    if (window.ActiveXObject) {
        xhrRegister = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else if (window.XMLHttpRequest) {
        xhrRegister = new XMLHttpRequest;
    }
    /* build query string */
    var strQuery = buildRegisterQuery();

    /* set up xhrRegister */
    xhrRegister.open("POST", "AccountServlet?timeStamp=" + new Date().getDate(), true);
    xhrRegister.onreadystatechange = handleRegisterResponse;
    xhrRegister.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    xhrRegister.send(strQuery);

    /* processing... */
    document.getElementById("divSystemError").style.display = "inline";
    document.getElementById("divSystemError").innerHTML = "Processing...";
}
/*****************************************************************************/
function handleRegisterResponse() {

    if (xhrRegister.readyState != 4) return;
    if (xhrRegister.status != 200) return;

    /* remove all error messages */
    clearAllErrors();

    /* handle the response */
    var xhresponse = xhrRegister.responseXML;
    var nodErrors = xhresponse.getElementsByTagName("Error");

    if (nodErrors.length == 0) {
        window.location = "success.html";
        return;
    }
    /* handle the errors */
    var nodError;
    var iErrorCode;
    var strErrorMessage;

    for (var i = 0; i < nodErrors.length; i++) {
        nodError = nodErrors[i];

        iErrorCode = parseInt(nodError.getElementsByTagName("ErrorCode")[0].firstChild.nodeValue);
        strErrorMessage = nodError.getElementsByTagName("ErrorMessage")[0].firstChild.nodeValue;

        setError(iErrorCode, strErrorMessage)
    }
    /* display friendly error message */
    displayPopup("There are invalid fields. Kindly resolve the marked areas", "center", 2500);
}
/*****************************************************************************/
function buildRegisterQuery() {

    var strQuery;

    strQuery = "action=register&";

    strQuery += "new_pw=" + document.getElementById("txtPassword").value + "&";
    strQuery += "retype_pw=" + document.getElementById("txtRetypePassword").value + "&";
    strQuery += "fst_name=" + document.getElementById("txtFirstName").value + "&";
    strQuery += "lst_name=" + document.getElementById("txtLastName").value + "&";
    strQuery += "dob_yr=" + document.getElementById("txtDOB_Year").value + "&";
    strQuery += "dob_mth=" + document.getElementById("txtDOB_Month").value + "&";
    strQuery += "dob_day=" + document.getElementById("txtDOB_Day").value + "&";
    strQuery += "contact=" + document.getElementById("txtContact").value + "&";
    strQuery += "email=" + document.getElementById("txtEmail").value + "&";
    strQuery += "cc_num=" + document.getElementById("txtCreditCardNumber").value + "&";
    strQuery += "cc_cvv=" + document.getElementById("txtCreditCardCVV").value + "&";
    strQuery += "cc_yr=" + document.getElementById("selCreditCardYear").value + "&";
    strQuery += "cc_mth=" + document.getElementById("selCreditCardMonth").value + "&";
    strQuery += "cc_type=" + document.getElementById("selCreditCardType").value + "&";
    strQuery += "cc_hldr=" + document.getElementById("txtCreditCardHolder").value + "&";

    strQuery += "country=" + document.getElementById("selCountry").value + "&";
    strQuery += "city=" + document.getElementById("txtCity").value + "&";
    strQuery += "state=" + document.getElementById("txtState").value + "&";
    strQuery += "addr_l1=" + document.getElementById("txtAddressLine1").value + "&";
    strQuery += "addr_l2=" + document.getElementById("txtAddressLine2").value + "&";
    strQuery += "postal=" + document.getElementById("txtPostalCode").value + "&";

    if (document.forms[0].radSaveCreditCard[0].checked)
        strQuery += "save_cc=yes";
    else
        strQuery += "save_cc=no";
        
    return strQuery;
}
/*****************************************************************************/
function validate(field) {

    var strQuery;

    if (field == document.getElementById("txtCreditCardNumber"))
        strQuery = "action=v_cc_num&cc_num=" + field.value;

    else if (field == document.getElementById("txtEmail"))
        strQuery = "action=v_email&email=" + field.value + "&cust_id=" + getCookie("CustomerID");

    else if (field == document.getElementById("txtContact"))
        strQuery = "action=v_contact&contact=" + field.value;

    else if (field == document.getElementById("txtFirstName"))
        strQuery = "action=v_fst_name&fst_name=" + field.value;

    else if (field == document.getElementById("txtLastName"))
        strQuery = "action=v_lst_name&lst_name=" + field.value;
    
    else if (field == document.getElementById("selCreditCardType"))
        strQuery = "action=v_cc_issuer&cc_type=" + field.value + "&cc_num=" + document.getElementById("txtCreditCardNumber").value;

    else if (field == document.getElementById("selCreditCardMonth") || field == document.getElementById("selCreditCardYear"))
        strQuery = "action=v_cc_expiry&cc_mth=" + document.getElementById("selCreditCardMonth").value +
                   "&cc_yr=" + document.getElementById("selCreditCardYear").value;

    else if (field == document.getElementById("txtRetypePassword"))
        strQuery = "action=v_retype_pw&new_pw=" + document.getElementById("txtPassword").value +
                   "&retype_pw=" + field.value;
    
    else if(field == document.getElementById("txtDOB_Year") || field == document.getElementById("txtDOB_Month") || 
            field == document.getElementById("txtDOB_Day")) {

        /* help fix the year to yyyy */
        if (field == document.getElementById("txtDOB_Year"))
            fixYear(field);
        
        strQuery = "action=v_dob&dob_day=" + document.getElementById("txtDOB_Day").value +
                   "&dob_mth=" + document.getElementById("txtDOB_Month").value +
                   "&dob_yr=" + document.getElementById("txtDOB_Year").value;    
    }
    else {
        alert("no field to validate"); // for debugging
        return;
    }
    
    vfield = field;

    /* Create xhrValidate */
    if (window.ActiveXObject) {
        xhrValidate = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else if (window.XMLHttpRequest) {
        xhrValidate = new XMLHttpRequest;
    }

    /* set up xhrValidate */
    xhrValidate.open("POST", "AccountServlet?timeStamp=" + new Date().getDate(), true);
    xhrValidate.onreadystatechange = handleValidateResponse;
    xhrValidate.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    xhrValidate.send(strQuery);
}
/*****************************************************************************/
function handleValidateResponse() {

    if (xhrValidate.readyState != 4) return;
    if (xhrValidate.status != 200) return;

    var xhresponse = xhrValidate.responseXML;
    var nodErrors = xhresponse.getElementsByTagName("Error");

    if (nodErrors.length == 0) {
        /* remove respective error messages */
        if (vfield == document.getElementById("txtEmail"))
            hideDiv(document.getElementById("divEmailError"));

        else if (vfield == document.getElementById("txtCreditCardNumber"))
            hideDiv(document.getElementById("divCreditCardNumberError"));

        else if (vfield == document.getElementById("selCreditCardMonth") || vfield == document.getElementById("selCreditCardYear"))
            hideDiv(document.getElementById("divCreditCardExpiryError"));

        else if (vfield == document.getElementById("txtEmail"))
            hideDiv(document.getElementById("divEmailError"));

        else if (vfield == document.getElementById("txtFirstName"))
            hideDiv(document.getElementById("divFirstNameError"));

        else if (vfield == document.getElementById("txtLastName"))
            hideDiv(document.getElementById("divLastNameError"));

        else if (vfield == document.getElementById("txtContact"))
            hideDiv(document.getElementById("divContactError"));

        else if (vfield == document.getElementById("selCreditCardType"))
            hideDiv(document.getElementById("divCreditCardTypeError"));

        else if (vfield == document.getElementById("txtRetypePassword"))
            hideDiv(document.getElementById("divRetypePasswordError"));
        
        else if(vfield == document.getElementById("txtDOB_Year") || vfield == document.getElementById("txtDOB_Month") || 
                vfield == document.getElementById("txtDOB_Day"))
            hideDiv(document.getElementById("divDOB_Error"));
        else return;

        return;
    }
    //assert(nodErrors.length == 1);
    var iErrorCode = nodErrors[0].getElementsByTagName("ErrorCode")[0].firstChild.nodeValue;
    var strErrorMessage = nodErrors[0].getElementsByTagName("ErrorMessage")[0].firstChild.nodeValue;
    setError(parseInt(iErrorCode), strErrorMessage);
}
/*****************************************************************************/
/* xhrPasswordStrength */
function getPasswordStrength(field) {

    /* Create xhrPasswordStrength */
    if (window.ActiveXObject) {
        xhrPasswordStrength = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else if (window.XMLHttpRequest) {
        xhrPasswordStrength = new XMLHttpRequest;
    }
    /* build query string */
    var strQuery = 'action=pw_strength&pw=' + field.value;

    /* set up xhrValidate */
    xhrPasswordStrength.open("POST", "AccountServlet?timeStamp=" + new Date().getDate(), true);
    xhrPasswordStrength.onreadystatechange = handlePasswordStrength;
    xhrPasswordStrength.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    xhrPasswordStrength.send(strQuery);
}
/*****************************************************************************/
function handlePasswordStrength() {

    if (xhrPasswordStrength.readyState != 4) return;
    if (xhrPasswordStrength.status != 200) return;

    var xhresponse = xhrPasswordStrength.responseXML;

    var nodStrength = xhresponse.getElementsByTagName("Strength");

    if (nodStrength.length > 0)
        displayStrength(parseInt(nodStrength[0].firstChild.nodeValue));
    else
        hideStrength();
}
/*****************************************************************************/
function displayStrength(strength) {

    var divPasswordStrength = document.getElementById("divPasswordStrength");
    var divNewPasswordError = document.getElementById("divPasswordError");

    switch (strength) {
        case -2:
            showDiv(divNewPasswordError, "Too short");
            hideDiv(divPasswordStrength);
            break;
        case -1:
            showDiv(divNewPasswordError, "Too long");
            hideDiv(divPasswordStrength);
            break;
        case 0:
            showDiv(divNewPasswordError, "Password required");
            hideDiv(divPasswordStrength);
            break;
        case 1:
            showDiv(divPasswordStrength, "<img src='images/weak.png' class='imgPasswordStrength'/>");
            hideDiv(divNewPasswordError);
            break;
        case 2:
            showDiv(divPasswordStrength, "<img src='images/moderate.png' class='imgPasswordStrength'/>");
            hideDiv(divNewPasswordError);
            break;
        case 3:
            showDiv(divPasswordStrength, "<img src='images/strong.png' class='imgPasswordStrength'/>");
            hideDiv(divNewPasswordError);
            break;
        case 4:
            showDiv(divPasswordStrength, "<img src='images/very_strong.png' class='imgPasswordStrength'/>");
            hideDiv(divNewPasswordError);
            break;
        default: hideStrength();
    }
}
/*****************************************************************************/
function hideStrength() {

    var divPasswordStrength = document.getElementById("divPasswordStrength");
    divPasswordStrength.style.display = "none";
    divPasswordStrength.innerHTML = "";
}
/*****************************************************************************/

/* Credit card */
function showCreditCardFieldset() {
    document.getElementById("fsetCreditCardDetails").style.visibility = "visible";
}
/*****************************************************************************/
function hideCreditCardFieldset() {
    document.getElementById("fsetCreditCardDetails").style.visibility = "hidden";
}
/*****************************************************************************/

/* helpers */
function setError(code, msg) {

    switch (code) {
        case SYS_ERR:
            showDiv(document.getElementById("divSystemError"), msg);
            break;

        case EMAIL_NT_UNIQUE: case INVALID_EMAIL: case NULL_EMAIL:
            showDiv(document.getElementById("divEmailError"), msg);
            break;

        case INVALID_CONTACT:
            showDiv(document.getElementById("divContactError"), msg);
            break;

        case INVALID_CC_EXPIRY: case CC_EXPIRED:
            showDiv(document.getElementById("divCreditCardExpiryError"), msg);
            break;

        case INVALID_CC_NUM:
            showDiv(document.getElementById("divCreditCardNumberError"), msg);
            break;

        case INVALID_CC_ISSUER:
            showDiv(document.getElementById("divCreditCardTypeError"), msg);
            break;

        case NULL_FST_NAME:
            showDiv(document.getElementById("divFirstNameError"), msg);
            break;

        case NULL_LST_NAME:
            showDiv(document.getElementById("divLastNameError"), msg);
            break;
        
        case PWD_MISMATCH:
            showDiv(document.getElementById("divRetypePasswordError"), msg);
            break;

        case NULL_PWD: case INVALID_PWD:
            showDiv(document.getElementById("divPasswordError"), msg);
            hideDiv(document.getElementById("divPasswordStrength"));
            break;
            
        case INVALID_DOB: case NULL_DOB:
            showDiv(document.getElementById("divDOB_Error"), msg);
            break;
    }
}
/*****************************************************************************/
function clearAllErrors() {

    hideDiv(document.getElementById("divFirstNameError"));
    hideDiv(document.getElementById("divLastNameError"));
    hideDiv(document.getElementById("divContactError"));
    hideDiv(document.getElementById("divCreditCardNumberError"));
    hideDiv(document.getElementById("divCreditCardExpiryError"));
    hideDiv(document.getElementById("divCreditCardTypeError"));
    hideDiv(document.getElementById("divEmailError"));
    hideDiv(document.getElementById("divSystemError"));
    hideDiv(document.getElementById("divPasswordError"));
    hideDiv(document.getElementById("divRetypePasswordError"));
    hideDiv(document.getElementById("divDOB_Error"));
    hideDiv(document.getElementById("divPasswordStrength"));
}
/*****************************************************************************/
function clearError(div) {
    hideDiv(div);
}
/*****************************************************************************/
function resetForm() {

    document.forms.item(0).reset(); /* clear all inputs */

    clearAllErrors();               /* clear all errors */
    
    hideCreditCardFieldset();       /* hide Credit Card Details fieldset */
}
